package thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description: 实现一个固定线程数量的线程池
 * User: 王圆豪
 * Date: 2025-05-04
 * Time: 23:15
 */
class MyPool{
    private BlockingQueue<Runnable> q = null;

    public MyPool(int cap) throws InterruptedException {
        q = new ArrayBlockingQueue<>(1000);
        for (int i = 0; i < cap; i++) {
            Thread t = new Thread(()->{
                while (true) {
                    try {
                        Runnable runnable = q.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }
    }

    public void submit(Runnable runnable) throws InterruptedException {
        q.put(runnable);
    }

}

public class Demo31 {
    public static void main(String[] args) throws InterruptedException {
        MyPool myPool = new MyPool(100);
        for (int i = 0; i < 100; i++) {
            int id = i;
            myPool.submit(()->{
                System.out.println(id + "......" + Thread.currentThread().getName());
            });
        }
    }
}
